
<template>
  <div class="app-container">
    <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
      <el-form-item label="文章标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入文章标题"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="是否上架" prop="available">
        <el-select v-model="queryParams.available" clearable placeholder="请选择" size="small">
          <el-option
            v-for="item in boolOptions"
            :key="item.dictValue"
            :label="item.dictLabel"
            :value="item.dictValue.toString()"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="是否置顶" prop="topFlag">
        <el-select v-model="queryParams.topFlag" clearable placeholder="请选择" size="small">
          <el-option
            v-for="item in boolOptions"
            :key="item.dictValue"
            :label="item.dictLabel"
            :value="item.dictValue.toString()"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="是否评论" prop="commentFlag">
        <el-select v-model="queryParams.commentFlag" clearable placeholder="请选择" size="small">
          <el-option
            v-for="item in boolOptions"
            :key="item.dictValue"
            :label="item.dictLabel"
            :value="item.dictValue.toString()"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="发布时间" prop="publishTime">
        <el-date-picker
          v-model="queryParams.publishTime"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          size="small"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="创建时间" prop="createdAt">
        <el-date-picker
          v-model="queryParams.createdAt"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          size="small"
        ></el-date-picker>
      </el-form-item>
      

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-permisaction="['cms:archives:add']"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-permisaction="['cms:archives:edit']"
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-permisaction="['cms:archives:remove']"
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="ArticleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="封面图片"
        align="center"
        prop="image"
        width="180"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <div style="display: flex;flex-wrap: nowrap;">
            <div v-for="(item,index) in scope.row.image" :key="index">
              <img :src="item.url" style="width:auto ;height:40px;margin-right:5px" />
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="文章标题"
        align="center"
        prop="title"
        width="180"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="标签"
        align="center"
        prop="tags"
        width="120"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <div v-for="(item,index) in scope.row.tags" :key="index">
            <el-tag size="mini">{{item.name}}</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="作者"
        align="center"
        prop="authorInfo"
        :show-overflow-tooltip="true"
        width="120"
      >
        <template slot-scope="scope">
          <div>
            <img
              :src="scope.row.authorInfo.avatar"
              style="width:auto ;height:40px;margin-right:5px"
            />
            {{scope.row.authorInfo.nickname}}
          </div>
        </template>
      </el-table-column>

      <el-table-column label="点击数" align="center" prop="hit" :show-overflow-tooltip="true" />
      <el-table-column label="回复数" align="center" prop="replyNum" :show-overflow-tooltip="true" />
      <el-table-column label="点赞数" align="center" prop="upVote" :show-overflow-tooltip="true" />
      <el-table-column label="差评数" align="center" prop="downVote" :show-overflow-tooltip="true" />
      <el-table-column label="收藏数" align="center" prop="favourite" :show-overflow-tooltip="true" />
      <el-table-column label="是否上架" align="center" prop="available" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.available"
            active-value="T"
            inactive-value="F"
            @change="handleSwitchChange(scope.row,'available','上架')"
          />
        </template>
      </el-table-column>
      <el-table-column label="是否置顶" align="center" prop="topFlag" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.topFlag"
            active-value="T"
            inactive-value="F"
            @change="handleSwitchChange(scope.row,'topFlag','置顶')"
          />
        </template>
      </el-table-column>

      <el-table-column label="是否评论" align="center" prop="commentFlag" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.commentFlag"
            active-value="T"
            inactive-value="F"
            @change="handleSwitchChange(scope.row,'commentFlag','评论')"
          />
        </template>
      </el-table-column>

      <el-table-column
        label="发布时间"
        align="center"
        prop="publishTime"
        :show-overflow-tooltip="true"
        width="165"
      />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createdAt"
        :show-overflow-tooltip="true"
        width="165"
      />
      <el-table-column
        label="更新时间"
        align="center"
        prop="updatedAt"
        :show-overflow-tooltip="true"
        width="165"
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="180"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            v-permisaction="['cms:archives:edit']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            v-permisaction="['cms:arhives:comment']"
            size="mini"
            type="text"
            icon="el-icon-s-comment"
            @click="handleComment(scope.row)"
          >评论</el-button>
          <el-button
            v-permisaction="['cms:archives:remove']"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageIndex"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-drawer :title="title" :visible.sync="open" size="50%">
      <div class="demo-drawer__content">
        <el-form
          ref="elForm"
          :model="form"
          :rules="rules"
          size="medium"
          label-width="100px"
          style="width:90%"
        >
          <el-row :gutter="15">
            <el-form-item label="栏目" prop="categoryIdList">
              <el-cascader
                v-model="form.categoryIdList"
                :options="categoryIdsOptions"
                :style="{width: '100%'}"
                placeholder="请选择栏目"
                filterable
                clearable
              ></el-cascader>
            </el-form-item>
            <el-form-item label="标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入标题" clearable :style="{width: '100%'}"></el-input>
            </el-form-item>
            <el-form-item label="发布时间" prop="publishTime">
              <el-date-picker v-model="form.publishTime" type="datetime" placeholder="请选择发布时间" value-format="yyyy-MM-dd HH:mm:ss" clearable></el-date-picker>

              <!-- <el-date-picker
                type="date"
                v-model="form.publishTime"
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd"
                :style="{width: '100%'}"
                placeholder="请选择发布时间"
                clearable >
              </el-date-picker>-->
            </el-form-item>
            <el-form-item label="是否上架" prop="available">
              <el-switch v-model="form.available" active-value="T" inactive-value="F"></el-switch>
            </el-form-item>
            <el-form-item label="是否置顶" prop="topFlag">
              <el-switch v-model="form.topFlag" active-value="T" inactive-value="F"></el-switch>
            </el-form-item>
            <el-form-item label="是否评论" prop="commentFlag">
              <el-switch v-model="form.commentFlag" active-value="T" inactive-value="F"></el-switch>
            </el-form-item>

            <el-form-item label="图片" prop="Image">
              <el-upload
                ref="upload"
                name="upload"
                :action="uploadImageAction"
                :headers="myHeader"
                list-type="picture-card"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
                :multiple="true"
                :limit="9"
                :file-list="form.image"
                :on-success="handlepostingImageSuccess"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="摘要" prop="description">
              <el-input
                v-model="form.description"
                type="textarea"
                placeholder="请输入摘要"
                :autosize="{minRows: 4, maxRows: 4}"
                :style="{width: '100%'}"
              ></el-input>
            </el-form-item>
            <el-form-item label="发布会员" prop="authorId">
              <el-select
                v-model="form.authorId"
                placeholder="请选择发布会员"
                filterable
                clearable
                :style="{width: '100%'}"
              >
                <el-option
                  v-for="item in officeuserOptions"
                  :key="item.userId"
                  :label="item.nickname"
                  :value="item.userId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="内容" prop="content" v-if="TinymceIsAble">
              <tinymce v-model="form.content.content" :height="300" ref="tinymce" />
            </el-form-item>
          </el-row>
          <el-row :gutter="15">
            <el-form-item label="标签" prop="tags">
              <el-tag
                :key="tag"
                v-for="tag in form.tags"
                closable
                :disable-transitions="false"
                @close="handleClose(tag)"
              >{{tag.name}}</el-tag>
              <el-input
                class="input-new-tag"
                v-if="inputVisible"
                v-model="inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm"
                @blur="handleInputConfirm"
              ></el-input>
              <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 新标签</el-button>
            </el-form-item>
            <el-form-item label="权重" prop="weigh">
              <el-input-number v-model="form.weigh" placeholder="权重"></el-input-number>
            </el-form-item>

            <el-form-item label="点击数" prop="hit">
              <el-input-number v-model="form.hit" placeholder="点击数"></el-input-number>
            </el-form-item>
            <el-form-item label="回复数" prop="replyNum">
              <el-input-number v-model="form.replyNum" placeholder="回复数"></el-input-number>
            </el-form-item>
            <el-form-item label="点赞数" prop="upVote">
              <el-input-number v-model="form.upVote" placeholder="点赞数"></el-input-number>
            </el-form-item>
            <el-form-item label="差评数" prop="downVote">
              <el-input-number v-model="form.downVote" placeholder="差评数"></el-input-number>
            </el-form-item>
            <el-form-item label="收藏数" prop="favourite">
              <el-input-number v-model="form.favourite" placeholder="收藏数"></el-input-number>
            </el-form-item>
          </el-row>
        </el-form>
        <div class="demo-drawer__footer" style="display: flex;justify-content: center;">
          <el-button @click="close">取消</el-button>
          <el-button type="primary" @click="handelConfirm">确定</el-button>
        </div>
      </div>

      <!-- <article_add   /> -->
    </el-drawer>

    <!-- 评论 start-->
    <el-dialog :title="titleComment" :visible.sync="openComment" width="80%" style="align-items:flex-start">
      <comment origin="archives" :originId="CommentArchivesId" />
    </el-dialog>
    <!-- 评论 end-->

    <!-- 图片预览 start-->
    <el-dialog :visible.sync="dialogVisible"  style="align-items:flex-start">
      <img width="100%" :src="dialogImageUrl" alt />
    </el-dialog>
    <!-- 图片预览 end-->
  </div>
</template>
<style >
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

/*1.显示滚动条：当内容超出容器的时候，可以拖动：*/
.el-drawer__body {
  -webkit-box-flex: 1;
  -ms-flex: 1;
  /* flex: 1; */
  overflow: auto;
}
/*2.隐藏滚动条，太丑了*/
.el-drawer__container ::-webkit-scrollbar {
  display: none;
}
</style>

<script>
import {
  listArchives,
  getArchives,
  delArchives,
  addArchives,
  updateArchives,
} from "@/api/cms/archives";

//调用编辑器
import Tinymce from "@/components/Tinymce";

import { getToken } from "@/utils/auth";

import comment from "@/components/MyComment";

export default {
  name: "cms_archives",
  components: {
    //使用编辑器
    Tinymce,
    comment,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 参数表格数据
      configList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 类型数据字典
      typeOptions: [],
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageIndex: 1,
        pageSize: 10,
        publishTime: undefined,
        title: undefined,
        keywords: undefined,
        tags: undefined,
        commentFlag: undefined,
        topFlag: undefined,
        createdAt: undefined,
        updatedAt: undefined,
        available: undefined,
      },
      form: {
        categoryIds: null,
        categoryIdList: [],
        title: undefined,
        publishTime: null,
        available: "T",
        commentFlag: "T",
        topFlag: "F",
        description: undefined,
        authorId: undefined,
        tags: [],
        hit: 0,
        replyNum: 0,
        upVote: 0,
        downVote: 0,
        favourite: 0,
        weigh: 0,
        content: {
          content: "",
        },
        image: [],
        authorInfo: {
          avatar: "",
          nickname: "",
        },
      },
      rules: {
        categoryIdList: [
          {
            required: true,
            type: "array",
            message: "请至少选择一个文档分类",
            trigger: "change",
          },
        ],
        title: [
          {
            required: true,
            message: "请输入标题",
            trigger: "blur",
          },
        ],
        publishTime: [
          {
            required: true,
            message: "请选择发布时间",
            trigger: "change",
          },
        ],
        description: [],
        authorId: [
          {
            required: true,
            message: "请至少选择一个发布会员",
            trigger: "change",
          },
        ],
        content: [
          {
            required: true,
            message: "请输入内容",
            trigger: "blur",
          },
        ],
        tags: [],
        hit: [],
        replyNum: [],
        upVote: [],
        downVote: [],
        favourite: [],
      },

      categoryIdsOptions: [],

      //文章列表
      ArticleList: null,
      //标签组建
      inputVisible: false,
      inputValue: "",
      //图片预览
      uploadImageAction:
        process.env.VUE_APP_BASE_API + "/api/v1/common/uploadImage",
      dialogImageUrl: null,
      dialogVisible: false,
      myHeader: {
        Authorization: "Bearer " + getToken(),
      },
      //官方用户列表
      officeuserOptions: [],
      //是否显示评论弹出层
      openComment: false,
      //评论弹出层标题
      titleComment: "",
      //查看评论的帖子ID
      CommentArchivesId: undefined,
      //是否
      boolOptions: [],
      //文本编辑器是否可用
      TinymceIsAble: true,
    };
  },
  computed: {
    // editor() {
    //   return this.$refs.myQuillEditor.quill;
    // }
  },
  created() {
    this.getList();
    //查询文章分类
    this.getcategoryIdsOptions();
    this.officeuserOptions = this.$store.getters.parameter.general_user_office;
    this.boolOptions = this.$store.getters.parameter.sys_bool;
  },
  methods: {
    /** 查询参数列表 */
    getList() {
      this.loading = true;
      listArchives(this.addDateRange(this.queryParams, this.dateRange)).then(
        (response) => {
          this.ArticleList = response.data.list;
          this.total = response.data.count;
          this.loading = false;
          console.log(this.ArticleList);
        }
      );
    },

    // 表单重置
    reset() {
      //清空图片列表
      this.form = {
        categoryIds: null,
        categoryIdList: [],
        title: undefined,
        publishTime: null,
        available: "T",
        commentFlag: "T",
        topFlag: "F",
        description: undefined,
        authorId: undefined,
        tags: [],
        hit: 0,
        replyNum: 0,
        upVote: 0,
        downVote: 0,
        favourite: 0,
        weigh: 0,
        content: {
          content: "",
        },
        image: [],
        authorInfo: {
          avatar: "",
          nickname: "",
        },
      };
      this.resetForm("elForm");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageIndex = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加文章";
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.archivesId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      let that = this;
      that.TinymceIsAble = false;
      that.open = true;
      that.title = "修改文章";
      that.reset();
      const id = row.archivesId || that.ids;

      getArchives(id).then((response) => {
        console.log(response);
        that.form = response.data;
        that.TinymceIsAble = true;
        // that.$refs["tinymce"].setContent(that.form.content.content);
      });
    },
    //评论按钮操作
    handleComment(row) {
      console.log(row);
      this.CommentArchivesId = row.archivesId;
      this.openComment = true;
      this.titleComment = "评论";
    },

    /** 提交按钮 */
    handelConfirm: function () {
      this.$refs["elForm"].validate((valid) => {
        if (valid) {
          if (this.form.archivesId !== undefined) {
            updateArchives(this.form).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            addArchives(this.form).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const Ids = row.archivesId || this.ids;
      this.$confirm('是否确认删除标题为"' + row.title + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delArchives(Ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function () {});
    },

    // 文章状态修改
    handleSwitchChange(row, filed, tipStr) {
      const text = row[filed] === "T" ? "启用" : "停用";
      console.log(row[filed]);
      this.$confirm(
        '确认要"' + text + row.title + tipStr + '"功能吗?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          let updateData = {};
          updateData["archivesId"] = row.archivesId;
          updateData[filed] = row[filed];

          updateArchives(updateData).then((response) => {
            if (response.code === 200) {
              return true;
            } else {
              this.msgError("修改失败");
              return false;
            }
          });

          // return changeUserStatus(row.userId, row.status)
        })
        .then(() => {
          this.msgSuccess(text + row.title + tipStr + "成功");
          // this.getList();
        })
        .catch(function () {
          // row.status = row.status === "0" ? "1" : "0";
        });
    },

    onOpen() {},
    onClose() {},
    close() {
      this.open = false;
      this.reset();
    },

    getcategoryIdsOptions() {
      // TODO 发起请求获取数据
      this.categoryIdsOptions = this.$store.getters.parameter.cms_article_category;
    },

    //图片上传 start
    postingImageBeforeUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG && !isPNG) {
        this.$message({
          message: "上传图片只能是 JPG或PNG 格式!",
          type: "warning",
        });
        return false;
      }
      if (!isLt2M) {
        this.$message({
          message: "单个文件 " + file.name + " 不能大于2M",
          type: "warning",
        });
        return false;
      }
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
      this.form.image = fileList;
      console.log(this.form.image);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },

    //上传组图成功
    handlepostingImageSuccess(res, file) {
      console.log(res.data);
      if (res.code == "200") {
        this.form.image.push(res.data);
      }

      console.log(this.form.image);
    },

    //图片上传 end

    //标签选择函数 start
    handleClose(tag) {
      this.form.tags.splice(this.form.tags.indexOf(tag), 1);
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        let tagsObj = {
          name: inputValue,
        };
        this.form.tags = this.form.tags.concat(tagsObj);
      }
      this.inputVisible = false;
      this.inputValue = "";
    },
    //标签选择函数 end
  },
};
</script>